﻿/*Cookies操作开始*/
(function () {
    window.Cookies = function (name) {
        return new GetSelectCookie(name);
    }
    var GetSelectCookie = function (name) {
        this.obj = name,
            this.expires = 30;
    }
    GetSelectCookie.prototype = {
        val: function (v) {
            if (v == null) {
                var cookie = document.cookie.match(new RegExp("(^|)" + this.obj + "=([^;]*)(;|$)"));
                if (cookie != null) {
                    return cookie[2];
                }
                return null;
            } else {
                var days = new Date();
                days.setTime(days.getTime() + this.expires * 60 * 60 * 1000);
                document.cookie = this.obj + "=" + v + ";expires=" + days.toGMTString();
            }
        },
        Append: function (v) {//向指定的Cookie后面追加信息，用$隔开
            var cookies = this.val();
            var date = new Date();
            date.setTime(date.getTime() + this.expires * 60 * 60 * 1000);
            if (cookies != null) {
                document.cookie = this.obj + "=" + cookies + "$" + v + ";expires=" + date.toGMTString();
            } else {
                document.cookie = this.obj + "=" + v + ";expires=" + date.toGMTString();
            }
        },
        ToArray: function () {
            var cookieList = this.val();
            if (cookieList != null) {
                return cookieList.split("$");
            }
            return null;
        },
        Remove: function () {
            var date = new Date();
            date.setTime(date.getTime() - 1);
            document.cookie = this.obj + "=;expires=" + date.toGMTString();
        },
        RemoveLikeAt: function (v) {
            var CookieList = this.ToArray();
            var cookies = "";
            if (CookieList != null) {
                for (var i = 0; i < CookieList.length; i++) {
                    if (CookieList[i].lastIndexOf(v)) {
                        cookies += CookieList[i] + "$";
                    }
                }
            }
            cookies = cookies.substring(0, cookies.length - 1);
            this.val(cookies);
        },
        IndexOf: function (v) {
            var result = -1;
            var CookieList = this.ToArray();
            if (CookieList != null) {
                for (var i = 0; i < CookieList.length; i++) {
                    if (!CookieList[i].lastIndexOf(v)) {
                        result = 1;
                        break;
                    }
                }
            }
            return result;
        }
    }
})()
/*Cookies操作结束*/
String.prototype.Trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
function removeHTMLTag(str) {
    str = $.trim(str);
    str = str.replace(/</g, "");
    str = str.replace(/\//g, "");
    str = str.replace(/>/g, "");
    str = str.replace(/\?/g, "");
    str = str.replace(/\*/g, "");
    return str;
}
/*
listid:要被点击的父级id
tabdiv:tab切换点击事件的id,去除_索引
count:tab总数
className:点击后的样式className
*/
function Tab(listid, tabdiv, count, className) {
    $(listid + " a").click(function () {
        var idlist = $(this).attr("id");
        var id = idlist.split("_");
        for (var i = 1; i <= count; i++) {
            if (i == id[1]) {
                $(tabdiv + i).show();
                $("#" + id[0] + "_" + i).addClass(className);
            } else {
                if (i != 6) {
                    $(tabdiv + i).hide();
                    $("#" + id[0] + "_" + i).removeClass(className);
                } else {
                    if (id[0] != "id") {
                        $(tabdiv + i).hide();
                        $("#" + id[0] + "_" + i).removeClass(className);
                    }
                }
            }
        }
    })
}

/*
listid:要被点击的父级id
tabdiv:tab切换点击事件的id,去除_索引
count:tab总数
className:点击后的样式className
*/
function TabMouseover(listid, tabdiv, count, className) {
    $(listid + " a").mouseover(function () {
        var idlist = $(this).attr("id");
        var id = idlist.split("_");
        for (var i = 1; i <= count; i++) {

            if (i == id[1]) {

                $(tabdiv + i).show();
                $("#" + id[0] + "_" + i).addClass(className);
            } else {
                if (i != 6) {
                    $(tabdiv + i).hide();
                    $("#" + id[0] + "_" + i).removeClass(className);
                } else {
                    if (id[0] != "id") {
                        $(tabdiv + i).hide();
                        $("#" + id[0] + "_" + i).removeClass(className);
                    }
                }
            }
        }
    })
}

//获取类别信息
function ShowCategoryList(id, count, layOutCss) {
    if (count) { } else { count = 0; }
    if ($(id).html().length > 100) { return; }

    $.ajax({
        type: "POST",
        cache: true,
        url: "/Category/GetCategoryList?&count=" + count + "&layOutUiCss=" + layOutCss,
        success: function (date) {
            if (AjaxValidate(date)) {
                if (date != null) {
                    $(id).html(date);
                }
            } else {
                $(id).html("加载类别失败");
            }
        }, error: function (e) {
            $(id).html("加载类别失败");
        }
    })
    return false;


}
/*  id:   ul的id
id1:  要显示的id
id3:  鼠标经过要绑定的id
*/
function Showul(id, id1, id2) {
    $(id + " li").mouseover(function () {
        var liidlist = $(this).attr('id');
        var display = $(this).css("display");
        var liid = liidlist.split('_');

        if (liid[0] == id1) { return; }
        $(this).css("display", "none");


        $(id1 + liid[1]).css("display", "block");
        var i = $(id + " li").length;
        for (var j = 0; j < i; j++) {
            if (j != liid[1]) {
                $(id2 + j).css("display", "block");
                $(id1 + j).css("display", "none");
            }
        }
    })
}
/*收藏代码
title:网站title
url:网站地址
*/
function addBookmark() {
    try {
        window.external.addFavorite(window.location.href, document.title);
    }
    catch (e) {
        try {
            window.sidebar.addPanel(document.title, window.location.href, "");
        }
        catch (e) {
            alert("加入收藏失败，请使用Ctrl+D进行添加");
        }
    }
}
/*
异步加载js
url:js url
callback加载完回调的函数
*/
function loadScript(url, callback) {
    setTimeout(function () {
        //创建script
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
        //加载完毕回调
        if (script.readyState) { //for IE
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;

                    if (callback) { callback(); }
                }
            };
        } else { //for Others

            script.onload = function () {
                if (callback) { callback(); }
            };
        }
    }, 0);
}
/*弹出框开始
s:要显示的提示信息
type:显示类型：不传显示叹号，1为对号，2为叹号
*/
window.alert = function (s, type) {
    if (s == "out") { return; }
    var error = "";
    var Isflush = false;
    s = s.replace("'", " ");
    if (s == "request error") {
        s = "请求失败，请刷新页面或重试";
        Isflush = true;
    }
    error += "<table cellspacing=\"0\" cellpadding=\"0\" align=\"center\"><tbody><tr><td>";
    if (type == 1) {
        error += "<span class=\"pop_c4\"></span>";
    } else {
        error += "<span class=\"pop_c3\"></span>";
    }
    error += "</td><td class=\"align-vm align-tl lh25\">" + s + "</td></tr></tbody></table>";
    $("#ErrorShow").html(error);
    $("#showError").show();
    ShowBack();
    timeclose = 0;
    SettimeCloseAlter();
    //    if (Isflush) {
    //        setTimeout(function () {
    //            window.location.href = window.location.href;
    //        }, 3000)
    //    }
}
function ShowBack() {
    //    var docheight = $(document).height();
    //    var docwidth = $(document).width();
    //    var clientWidth = document.documentElement.clientWidth == 0 ? document.body.clientWidth : document.documentElement.clientWidth;
    //    var docscrollleft = document.documentElement.scrollLeft == 0 ? document.body.scrollLeft : document.documentElement.scrollLeft;
    //    var docscroll = document.documentElement.scrollTop == 0 ? document.body.scrollTop : document.documentElement.scrollTop;
    //    $("#greybackground").css({ "opacity": "0.5", "height": docheight, "width": clientWidth + docscrollleft });
    SetShowBack();
    $("#greybackground").show();

}
var showBackTime = 0;
var showTime;
function SetShowBack() {
    var docheight = $(document).height();
    var docwidth = $(document).width();
    var clientWidth = document.documentElement.clientWidth == 0 ? document.body.clientWidth : document.documentElement.clientWidth;
    var docscrollleft = document.documentElement.scrollLeft == 0 ? document.body.scrollLeft : document.documentElement.scrollLeft;
    var docscroll = document.documentElement.scrollTop == 0 ? document.body.scrollTop : document.documentElement.scrollTop;
    $("#greybackground").css({ "opacity": "0.5", "height": docheight, "width": clientWidth + docscrollleft });
    showTime = setTimeout(SetShowBack, 1000);
}
function HideBack() {
    $("#greybackground").hide();
    timeclose = 0;
    clearTimeout(showTime);
}
var timeclose = 0;
var t;
function CloseAlter() {
    $("#ErrorShow").html("");
    $("#showError").hide();
    HideBack();
    timeclose = 0;
    clearTimeout(t);
}
function SettimeCloseAlter() {
    if (timeclose < 3) {
        t = setTimeout(SettimeCloseAlter, 800);
        timeclose++;
    } else {
        CloseAlter();
        timeclose = 0;
    }
}
var hideLodding = 0;
function Loadding(type) {
    if (type == "hide") {
        hideLodding = 0;
        HideLoadding();
    } else if (type == "show") {
        ShowBack();
        timeclose = 0;
        $("#Noback").show();
    }
}
function HideLoadding() {
    if (hideLodding == 1) {
        if (timeclose == 0) {
            HideBack();
        }
        $("#Noback").hide();
    } else {
        setTimeout(HideLoadding, 800);
        hideLodding++;
    }
}
/*弹出框结束*/

/*
弹出登录注册框
type:1登录，2注册
*/
function ShowLoginHeader(type) {
    var showlogin = new ShowLoginWindow();
    showlogin.CallBackFunc = function () { ShowHeaderLogin(); };
    if (type == 1) {
        showlogin.type = 1;
        showlogin.ShowLogin(showlogin);
    } else if (type == 2) {
        showlogin.type = 2;
        showlogin.ShowLogin();
    }

}
//调用示例
/*var showlogin = new ShowLoginWindow();
showlogin.CallBackFunc = function () { window.location.href = "/Shopping/Check"; };
showlogin.type = 1;
showlogin.ShowLogin();
$("#windowLogin").click(function () {
LoginOn(showlogin);
});
type:1为登录，2为注册
*/
function ShowLoginWindow() {
    /*默认title显示文字*/
    this.message = "",
    /*默认弹出登录框类型*/
    this.type = 0,
    /*登录成功后回调函数,默认为到订单页面，可以在调用时重写*/
    this.CallBackFunc = null,
    this.ShowLogin = function (showlogin) {
        ShowBack();
        //$("#login_title").html(this.message);
        $("#showLogin").show();
        if (this.type == 1) {
            $("#loginHtml").show();
            $("#registerHtml").hide();
            if ($("#loginHtml").html().length < 100) {
                ShowLoginHtml("/Account/ShowLogin", this.type, this.message, showlogin);
                $(document).scrollTop(0);
            } else {
                $(document).scrollTop(0);
                $("#txtLoginPwd").val("");
                $("#txtoldcode").val("");
                $("#txtLoginUid").focus();
                if (this.message != "") {
                    //$("#messageError").show();
                    $("#message").html(this.message);
                } else {
                    $("#messageError").hide();
                }
            }
        } else if (this.type == 2) {
            $("#registerHtml").show();
            $("#loginHtml").hide();
            if ($("#registerHtml").html().length < 100) {
                ShowLoginHtml("/Account/ShowRegister", this.type, this.message);
                $(document).scrollTop(0);
            } else {
                $(document).scrollTop(0);
                $("#txtRegisterPwd").val("");
                $("#newtxtRegisterPwd").val("");
            }
        }
    }
}
/*
显示登录注册弹出框
url:要显示的局部页url,
type：1为登录，2为注册
message:"要显示的提示语信息，暂时不用"
showlogin:请求成功后要执行的函数
*/
function ShowLoginHtml(url, type, message, showlogin) {
    if (!message) { message = ""; }
    $.ajax({
        type: "POST",
        url: url,
        success: function (date) {
            if (AjaxValidate(date)) {
                if (type == 1) {
                    //date = date.replace("{message}", message);
                    $("#loginHtml").html(date);
                    if (showlogin) {
                        $("#windowLogin").click(function () {
                            LoginOn(showlogin);
                        });
                    }
                }
                else {
                    $("#registerHtml").html(date);
                }
            }
        }, error: function () {
            alert("请求失败，请重试");
        }
    })
}
$(document).ready(function () {
    $("#addBookmark").click(function () {
        addBookmark();
    });
    $("[name='btnbutton']").each(function () {
        var className = $(this).attr("class");
        var id = $(this).attr("id");

        var classlist = className.split(' ');
        var classOld = classlist[0];

        if (!classOld) {
            classOld = classlist[1];
        }
        var newClass = className.replace(classOld, classOld + "_2");
        $("#" + id).mouseover(function () {


            $(this).removeClass(className).addClass(newClass);
        });
        $("#" + id).mouseout(function () {
            $(this).removeClass(newClass).addClass(className);
        });
    })
})

// 删除页头上的购物车数据
function DeleteHearCartItem(sysNo, listControl) {
    $.ajax({
        type: 'POST',
        url: '/Shopping/DeleteCart?sysNo=' + sysNo + '&type=1' + '&addProductToDeleteCookie=1',
        success: function (date) {
            if (AjaxValidate(date)) {
                BindHearCartList(listControl);
                var url = window.location.href.toLowerCase();
                if (url.indexOf("cart/index") >= 0) {
                    ShowCart();
                    ShowDeletedProductInfo();
                }
            }
        }
    })
}

$(document).ready(function () {
    // InitHeaderCartList();    
    /*页面js效果绑定原Submenu.js内容*/
    $('.allsortth').mousemove(function () {
        $(this).find('.allsortthin').addClass('thhover');
    });
    $('.cartftb').mousemove(function () {
        $(this).find('dl').addClass('carthover');
    });
    $('.listsum-1').click(function (e) {
        if (e.target != "javascript:;") {
            var className = $(this).find('dl').attr("class");
            if (className == "listhover") {
                $(this).find('dl').removeClass("listhover");
            } else {
                $(this).find('dl').addClass('listhover').end().siblings().find("dl").removeClass("listhover");
            }
        }
    });
    $('.setredwarp').click(function () {

        $(this).find('.setredmw').addClass('setredhover');
    });
    $('.cartftb').mouseleave(function () {
        $(this).find('dl').removeClass('carthover');
    });
    $('.allsortth').mouseleave(function () {
        $(this).find('.allsortthin').removeClass('thhover');
    });
    /*页面js效果绑定原Submenu.js内容结束*/
});
// 绑定页头购物车中的数据
function BindHearCartList(listControl) {
    $.ajax({
        type: "POST",
        url: "/Shopping/GetHeaderCartList",
        success: function (date) {
            if (AjaxValidate(date)) {
                if (date != null) {
                    $(listControl).html(date);
                    BindButtonCss("btnGotoCart", "butn5_2", "butn5");
                } else {
                    $(listControl).empty();
                    $(listControl).html("");
                }
                lazyLoad.Run();
            }
        }, error: function (e) {
            $(listControl).html("加载购物车信息失败");
        }
    })
}

function BindButtonCss(id, mouseoverCss, mouseoutCss) {

    $("#" + id).mouseover(function () {

        $(this).removeClass(mouseoutCss).addClass(mouseoverCss);
    });
    $("#" + id).mouseout(function () {
        $(this).removeClass(mouseoverCss).addClass(mouseoutCss);
    });
}
/* 
加入购物车
pSysNos：产品SysNo列表，用,号隔开
*/

function AddShoppingCartCompare(pSysNos) {
    $.ajax({
        type: 'POST',
        url: '/Shopping/AddShoppingcartForCompare?pSysNos=' + pSysNos,
        cache: false,
        success: function (date) {
            if (AjaxValidate(date)) {
                if (date == "添加失败，请稍后重试") {
                    alert("更新失败，请重试...");
                }
                else if (date == "非法的操作") {
                    alert("非法的操作");
                }
                else {
                    alert(date.replace("您共有", "共").replace("寄存在购物车", "").replace(/取出/g, "加入购物车"), 1);
                    //ShowCart(count);
                    BindHearCartList("#cartListView");
                }
            }
        }
    })
}
/*
加入购物车
加入购物车，1个
*/
function AddProductToCart(sysNo, count) {
    $.ajax({
        type: 'POST',
        url: '/Shopping/AddShoppingcart?productSysNo=' + sysNo + '&count=' + count + '&type=add',
        cache: false,
        success: function (date) {
            if (date == "商品已加入购物车") {
                BindHearCartList("#cartListView");
                alert("已成功加入购物车", 1);

            } else if (date == -1) {
                alert("该产品库存不足", 2);
            }
            else {
                alert(date);
            }
        }
    })
}
/*在线客服*/
function LoadCallCenter() {
    if ($("#iconDiv1").html() == "" || $("#iconDiv1").html().length < 100) {
        loadScript('/Scripts/kf.js', function () {

            $("#iconDivMain1").hide();
            $("#iconDivMain1 div").click();

        });
    } else {

        $("#iconDivMain1").hide();
        $("#iconDivMain1 div").click();
    }
}
/*Ajax操作验证*/
function AjaxValidate(date) {
    if (date) {
        if (date == "您输入或提交的信息中包含html标记或单引号等，请重新输入") {
            window.location.href = "/Error/Error?id=1003&msg=" + encodeURIComponent(date);
            return false;
        }
        if (date == "request error") {
            alert(date);
            return false;
        }
    }
    return true;
}
/*替换特殊字符*/
function KeyUp(key) {
    $(key + " input[type='text']").keyup(function () {
        var v = $(this).val();
        var bool = false;
        if (v.indexOf("<") >= 0) {
            v = v.replace(new RegExp(/(<)/g), '');
            bool = true;
        }
        if (v.indexOf(">") >= 0) {
            v = v.replace(new RegExp(/(>)/g), '');
            bool = true;
        }
        if (v.indexOf("'") >= 0) {
            v = v.replace(new RegExp(/(')/g), '');
            bool = true;
        }
        if (v.indexOf("$") >= 0) {
            v = v.replace(new RegExp(/($)/g), '');
            bool = true;
        } if (v.indexOf("&") >= 0) {
            v = v.replace(new RegExp(/(&)/g), '');
            bool = true;
        }
        if (bool == true) {
            $(this).val(v);
        }
    })
}